package com.xinghe.sharedevice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinghe.sharedevice.domain.Cabinet;
import com.xinghe.sharedevice.domain.Station;
import com.xinghe.sharedevice.domain.StationLocation;
import com.xinghe.sharedevice.mapper.StationMapper;
import com.xinghe.sharedevice.repository.StationLocationRepository;
import com.xinghe.sharedevice.service.ICabinetService;
import com.xinghe.sharedevice.service.IRegionService;
import com.xinghe.sharedevice.service.IStationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 星河一叶Ck
 * @date 2025/5/28
 */

@Service
@Slf4j
@RequiredArgsConstructor
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {

    // 站点mapper
    private final StationMapper stationMapper;
    // 充电宝service
    private final ICabinetService cabinetService;
    // 地区service
    private final IRegionService regionService;
    private final StationLocationRepository stationLocationRepository;

    /**
     * 查询站点列表
     * @param station 搜索的条件
     * @return List<Station>
     */
    @Override
    public List<Station> selectStationList(Station station) {
        // 查询到所有的站点信息
        List<Station> list = stationMapper.selectStationList(station);
        // 将id都单独弄出来
        List<Long> CabinetIdList = list.stream().map(Station::getCabinetId).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(list)) {

            // 根据充电宝id查询充电宝编号
            List<Cabinet> cabinetList = cabinetService.list(new LambdaQueryWrapper<Cabinet>()
                    .in(Cabinet::getId, CabinetIdList));

            Map<Long, String> cabinetIdToCabinetNoMap = cabinetList
                    // 用map key是ID value是No
                    .stream().collect(Collectors.toMap(Cabinet::getId, Cabinet::getCabinetNo));

            // 给每一个list赋值No
            for (Station item : list) {
                item.setCabinetNo(cabinetIdToCabinetNoMap.get(item.getCabinetId()));
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addStation(Station station) {
        // 地区编号查询对应名称 插入到站点地址中
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        String fullAddress = provinceName + cityName + districtName + station.getAddress();
        station.setFullAddress(fullAddress);
        boolean save = this.save(station);

        StationLocation stationLocation = new StationLocation();
        stationLocation.setId(ObjectId.get().toString());
        stationLocation.setStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocation.setCreateTime(new Date());
        stationLocationRepository.save(stationLocation);
        return save ? 1 : 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateStation(Station station) {
        // 地区编号查询对应名称 插入到站点地址中
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        String fullAddress = provinceName + cityName + districtName + station.getAddress();
        station.setFullAddress(fullAddress);
        boolean edit = this.updateById(station);

        StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocationRepository.save(stationLocation);
        return edit ? 1 : 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int setData(Station station) {
        this.updateById(station);

        // 更正柜机使用状态
        Cabinet cabinet = cabinetService.getById(station.getCabinetId());
        cabinet.setStatus("1");
        cabinetService.updateById(cabinet);
        return 1;
    }

    @Override
    public void updateData() {
        List<Station> stationList = this.list();
        for (Station station : stationList) {
            StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
            if (stationLocation == null) {
                stationLocation = new StationLocation();
                stationLocation.setId(ObjectId.get().toString());
                stationLocation.setStationId(station.getId());
                stationLocation.setLocation(
                        new GeoJsonPoint(station.getLongitude().doubleValue(),
                                station.getLatitude().doubleValue()));
                stationLocation.setCreateTime(new Date());
                stationLocationRepository.save(stationLocation);
            }
        }
    }

    @Override
    public boolean removeBatchByIds(Collection<?> list) {
        for (Object id : list) {
            // 对mongodb对应的存储进行删除
            stationLocationRepository.deleteByStationId(Long.parseLong(id.toString()));
        }
        return super.removeBatchByIds(list);
    }
}
